import React from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as cartActions from '../store/actions/cart.action'

class Cart extends React.Component {

  constructor(props) {
    super()
  }

  componentDidMount() {
    console.log(this.props, 'cart props')
    const { GET_CARTS } = this.props
    GET_CARTS()
  }

  render() {
    const { carts, DELETE_CART, CHANGE_CART_COUNT } = this.props
    return (
      <section className="container content-section">
        <h2 className="section-header">购物车</h2>
        <div className="cart-row">
          <span className="cart-item cart-header cart-column">商品</span>
          <span className="cart-price cart-header cart-column">价格</span>
          <span className="cart-quantity cart-header cart-column">数量</span>
        </div>
        { carts.map((cart, index) => {
          return (
            <div className="cart-items" key={cart.id}>
              <div className="cart-row">
                <div className="cart-item cart-column">
                  <img className="cart-item-image" src={`http://localhost:3005${cart.thumbnail}`} width="100" height="100" alt={cart.title} />
                  <span className="cart-item-title">{ cart.title }</span>
                </div>
                <span className="cart-price cart-column">￥{ cart.price }</span>
                <div className="cart-quantity cart-column">
                  <input className="cart-quantity-input" type="number" value={ cart.count } onChange={(e) => {CHANGE_CART_COUNT({
                    id: cart.id,
                    count: e.target.value
                  })}} />
                  <button onClick={() => DELETE_CART({ id: cart.id, index})} className="btn btn-danger" type="button">删除</button>
                </div>
              </div>
            </div>
          )
        })}
        <div className="cart-total">
          <strong className="cart-total-title">总价</strong>
          <span className="cart-total-price">￥{carts.reduce((pre, cur) => {
            console.log(pre, 'pre')
            return pre + cur.count * cur.price
          }, 0)}</span>
        </div>
      </section>
    )
  }
}

const mapStateToProps = state => ({
  carts: state.carts
})

const mapDispatchToProps = dispatch => ({
  ...bindActionCreators(cartActions, dispatch)
})

export default connect(mapStateToProps, mapDispatchToProps)(Cart)